// 云函数入口文件
const cloud = require('wx-server-sdk')
const { authenticator } = require('otplib')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

// 云函数入口函数
exports.main = async (event, context) => {
  try {
    const { openId, code } = event

    if (!openId || !code) {
      return {
        success: false,
        message: '参数不完整'
      }
    }

    const db = cloud.database()
    const userCollection = db.collection('MFA')

    // 查询用户
    const user = await userCollection
      .where({
        openid: openId
      })
      .get()

    if (user.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const userData = user.data[0]

    // 检查用户是否已绑定MFA
    if (!userData.mfaBound || !userData.mfaSecret) {
      return {
        success: false,
        message: '用户未绑定MFA'
      }
    }

    // 验证TOTP代码
    const isValid = authenticator.verify({
      token: code,
      secret: userData.mfaSecret
    })

    return {
      success: isValid,
      message: isValid ? '验证成功' : '验证码无效或已过期'
    }
  } catch (error) {
    console.error('Verify MFA error:', error)
    return {
      success: false,
      error: error.message
    }
  }
}
